package com.SpringbootVue.exception;

import com.SpringbootVue.pojo.Result;
import com.mysql.cj.jdbc.exceptions.MysqlDataTruncation;
import org.springframework.util.StringUtils;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        e.printStackTrace();
        return Result.error(StringUtils.hasLength(e.getMessage())? e.getMessage() : "操作失败");
    }
    @ExceptionHandler(MysqlDataTruncation.class)
    public Result handleMysqlDataTruncation(MysqlDataTruncation e) {
        e.printStackTrace();
        return Result.error("数据过长，无法保存，请检查输入内容长度。");
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationException(MethodArgumentNotValidException e) {
        Map<String, String> errors = new HashMap<>();
        for (FieldError error : e.getBindingResult().getFieldErrors()) {
            errors.put(error.getField(), error.getDefaultMessage());
        }
        return Result.error("Validation failed"+errors);
    }
    @ExceptionHandler(SQLException.class)
    public Result handleSQLException(SQLException e) {
        e.printStackTrace();
        return Result.error("数据库异常，请联系管理员！");
    }

    @ExceptionHandler(IOException.class)
    public Result handleIOException(IOException e) {
        e.printStackTrace();
        return Result.error("网络异常，请检查网络连接！");
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public Result handleIllegalArgumentException(IllegalArgumentException e) {
        e.printStackTrace();
        return Result.error("非法参数异常：" + e.getMessage());
    }
    @ExceptionHandler(RuntimeException.class)
    public Result handleRuntimeException(RuntimeException e) {
        e.printStackTrace();
        return Result.error("运行时异常：" + e.getMessage());
    }

    @ExceptionHandler(NullPointerException.class)
    public Result handleNullPointerException(NullPointerException e) {
        e.printStackTrace();
        return Result.error("空指针异常，请联系管理员！");
    }

}
